package com.zwcl.glass.tools.service.impl;

import com.zwcl.common.core.excel.AbstractImportService;
import com.zwcl.common.core.utils.BeanUtils;
import com.zwcl.glass.tools.dto.AddressImportDto;
import com.zwcl.glass.tools.entity.RecommendAddress;
import com.zwcl.glass.tools.enums.AddressTypeEnum;
import com.zwcl.glass.tools.mapper.RecommendAddressMapper;
import com.zwcl.glass.tools.service.RecommendAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AddressImportServiceImpl  extends AbstractImportService<AddressImportDto, AddressImportDto> {
    @Autowired
    private RecommendAddressMapper recommendAddressMapper;

    @Autowired
    private RecommendAddressService recommendAddressService;

    @Override
    protected Consumer<List<AddressImportDto>> saveData(AddressImportDto param) {
        return (list) -> {
            List<RecommendAddress> l = new ArrayList<>(list.size());
            for (AddressImportDto dto : list) {
                try {
                    RecommendAddress d = new RecommendAddress();
                    BeanUtils.copyProperties(dto,d);
                    d.setPoiType(AddressTypeEnum.of(dto.getPoiTypeStr()).getValue());
                    l.add(d);
                } catch (Exception e) {
                    log.warn("地址导入解析错误，序号：{}，名称：{}，错误：{}", dto.getNo(),dto.getName(), e);
                }
            }
            if (!CollectionUtils.isEmpty(l)) {
                try {
                    //先删除这些个城市的数据
                    List<String> cityList =  l.stream().map(x->x.getCity()).distinct().collect(Collectors.toList());
                    recommendAddressService.deleteCityData(cityList);
                    recommendAddressMapper.batchInsert(l);
                    log.info("导入成功{}条",l.size());
                    //TODO:刷新这些城市的到缓存中去，这样计算距离会快一点
                }catch (Exception ex){
                    log.error("导入失败：{}",ex);
                }
            }
        };
    }

    //异步执行
    @Async
    public void importData(InputStream inputStream) {
        readExcel(inputStream, AddressImportDto.class, null);
    }
}
